<?php

namespace App\Models;

use Cache;

class Hu extends BaseModel
{
    protected $table = "card";

    const PREFIX = 'kwx_cards';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where=[], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function getAllCardsCache()
    {
        $cards = Cache::get(self::PREFIX);
        if (!$cards) {
            $cards = $this->getList();
            if ($cards) {
                $cards = $cards->toArray();
                Cache::forever(self::PREFIX, $cards);
            }
        }
        return $cards;
    }

    public function delCache()
    {
        Cache::forget(self::PREFIX);
    }

    //发牌
    public function dealCard($banker)
    {
        $cards = $this->getAllCardsCache();
        $index = mt_rand(1,3);
        $players = [1=>'host',2=>'r1',3=>'r2'];
        $data['playlist']['banker'] = $banker;
        shuffle($cards);
        foreach($players as $k=>$v) {
            $num = 13;
            if ($v == $banker) {
                $num = 14;
            }
            $data['playlist'][$v] = array_splice($cards, 0, $num);
        }
        $data['playlist']['payrest'] = $cards;
        $data['type'] = 3;
        return json_encode($data);
    }

    //打牌
    public function playCards($rid, $mid, $cid) {

    }
}